package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.sql.DataSource;
import javax.transaction.Transaction;

import org.springframework.stereotype.Repository;

import pojo.Customer;
import dao.CustomerDao;

@Repository(value="customerDao")
public class CustomerDaoImpl implements CustomerDao {
	@Resource(name="jpaDataSource")
	private EntityManagerFactory factory;
	private EntityManager manager = null;
	


	@Override
	public Customer addCustomer(Customer c) {
		manager =factory.createEntityManager();
		EntityTransaction ts= manager.getTransaction();
		ts.begin();
		manager.persist(c);
		ts.commit();
		manager.close();
		return c;
	}

	@Override
	public Customer findCustomer(String cname, String psd) {
//		String sql = "from customer where cname='"+cname+"' and password='"+psd+"'";
		String sql = "select c from customer c where c.cname=:cname and c.password=:psd";
		manager =factory.createEntityManager();
		EntityTransaction ts= manager.getTransaction();
		ts.begin();
		Query query = manager.createQuery(sql,Customer.class);
		query.setParameter("cname",cname);
		query.setParameter("psd", psd);
		ts.commit();
//		query.getSingleResult();
		List<Customer> list = query.getResultList();
		if(list!=null){
			manager.close();
			return list.get(0);
		}
		manager.close();
		return null;
	}

}





